import socket
import queue
import threading
import time
from parse_binary import parse_binary_file_save

# 创建UDP socket
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定本地地址和端口
local_addr = ('10.9.0.94', 6110)  # 参考网页。。。。。
udp_socket.bind(local_addr)
udp_socket.settimeout(1.0)  # 采集超时设置，默认5.0秒

# 创建一个全局变量作为缓存队列
data_queue = queue.Queue()

# 创建一个全局变量作为文件名，根据个人进行设置
file_name = "data_file.bin"

# 定义一个全局flag 用于退出数据采集线程
exit_flag = threading.Event()


# 程序启动提示词
def log_print():
    print('DeepDAQ Data acquisition WORKING ...... 按 Ctrl + C 可停止采集')


# 8通道数据采集线程
def receive_data():
    try:
        while not exit_flag.is_set():
            data = udp_socket.recv(1293)  # 参考网页。。。。。
            if exit_flag.is_set():
                break
            data_queue.put(data)
            # print(f"Received data: {data}")
    except KeyboardInterrupt:
        pass
    except socket.timeout:
        print("No data received within the timeout period.")
        pass
    except socket.error as e:
        print(f"Socket error: {e}")
        pass
    finally:
        udp_socket.close()
        print("receive_data thread exited. 按 Ctrl + C 推出程序")


# 8通道数据储存值二进制文件file_name，后期需根据需求自主定义文件名
def write_to_file():
    with open(file_name, "ab") as file:
        while not exit_flag.is_set():
            try:
                data = data_queue.get(timeout=2)
                # print(f"Stored to file: {data}")
                file.write(data)
            except queue.Empty as e:
                break
                # print(f"Stored to file: {data}")
    print("write_to_file thread exited. 按 Ctrl + C 推出程序")



if __name__ == "__main__":
    log_print()
    try:
        # 启动接收UDP数据的线程
        receive_thread = threading.Thread(target=receive_data)
        receive_thread.start()

        # 启动将数据写入文件的线程
        write_thread = threading.Thread(target=write_to_file)
        write_thread.start()

        # 主线程等待 KeyboardInterrupt
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("DeepDAQ exited")
        # 设置退出标志，通知线程退出
        exit_flag.set()

        # 主线程等待receive_thread线程退出
        receive_thread.join()

        # 主线程等待write_thread线程退出
        write_thread.join()

        # 关闭UDP socket
        udp_socket.close()


    # 停止采集后自动完成数据转换并保存至CSV，如果不需要可注释或删除相关代码
    save_path = 'output.csv'
    parse_binary_file_save(file_name, save_path)
    print("数据已保存至CSV。")